#include "dns_util.h"

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>

void close_socket(SOCKET * socket) {
	if (socket != NULL && *socket != INVALID_SOCKET) {
		close(*socket);
		*socket = INVALID_SOCKET;
	}
}

void close_all(va_list sockets) {
  SOCKET * socket = NULL;

  while ((socket = va_arg(sockets, SOCKET *)) != NULL)
    close_socket(socket);
}

void exit_syserr(char * func_name, SOCKET * socket, ...) {
  va_list sockets;
  va_start(sockets, socket);
	close_all(sockets);
  va_end(sockets);
	perror(func_name);
	exit(errno);
}

void exit_runerr(char * err_msg, int err_code, SOCKET * socket, ...) {
  va_list sockets;
  va_start(sockets, socket);
	close_all(sockets);
  va_end(sockets);
	fprintf(stderr, "%s\n", err_msg);
	exit(err_code);
}
